package com.cctc.juc.common.thread.threadpool.holder;

import com.cctc.juc.common.thread.ShutdownHookThread;
import com.cctc.juc.common.thread.threadpool.config.ThreadPoolConfig;
import com.cctc.juc.common.util.ThreadUtils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 混合型任务线程池。
 * - 懒汉式创建单例混合型任务线程池，用于执行混合型任务。
 */
public class MixedTargetThreadPoolLazyHolder {
    /**
     * 混合型任务线程池中的线程数量配置：
     * 首先从环境变量 mixed.thread.amount 中获取预先配置的线程数，如果没有配置，则采用默认配置数量 [128] 个。
     */
    private static final int MAXIMUM_POOL_SIZE = (null != System.getProperty(ThreadPoolConfig.MIXED_THREAD_AMOUNT)) ? Integer.parseInt(System.getProperty(ThreadPoolConfig.MIXED_THREAD_AMOUNT)) : ThreadPoolConfig.MIXED_MAXIMUM_POOL_SIZE;

    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
            MAXIMUM_POOL_SIZE, MAXIMUM_POOL_SIZE,
            ThreadPoolConfig.KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(ThreadPoolConfig.WORK_QUEUE_SIZE),
            new ThreadUtils.AppThreadFactory("mixed"),
            new ThreadPoolExecutor.DiscardPolicy()
    );

    public static ThreadPoolExecutor getExecutor() {
        return EXECUTOR;
    }

    static {
        // 允许回收空闲超时的核心线程
        EXECUTOR.allowCoreThreadTimeOut(true);
        // JVM 进程关闭时的钩子函数
        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread("混合型任务线程池", () -> {
            // 优雅终止线程池
            ThreadUtils.shutdownThreadPoolGracefully(EXECUTOR);
            return null;
        }));
    }

}
